package com.ourhours.message.rpc.reference.jiguang;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

@Component
@Slf4j
public class JiGuangRpc {

    /**
     * 生成极光推送对象PushPayload（采用java SDK）
     * @param userId
     * @param title
     * @param content
     * @param action
     * @return
     */
    public static PushPayload buildPushObject(String userId, String title, String content, String action) {
        Map<String, String> parm = new HashMap<>();
        parm.put("target", userId);
        parm.put("title", title);
        parm.put("content", content);
        parm.put("action", action);
        return PushPayload.newBuilder().setPlatform(Platform.android_ios()).setAudience(Audience.alias(userId))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(
                                AndroidNotification.newBuilder().addExtras(parm).setAlert(title).build())
                        .addPlatformNotification(IosNotification.newBuilder().addExtras(parm).setAlert(title).build())
                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(false).build()).build();// true-推送生产环境
        // false-推送开发环境（测试使用参数）.setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）

    }

    /**
     * 极光推送方法(采用java SDK)
     * @param userId
     * @param title
     * @param content
     * @param action
     * @return
     */
    public PushResult pushing(String outerAppKey,String outerSecret,String userId, String title, String content, String action) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(outerSecret,outerAppKey,null, clientConfig);
        PushPayload payload = buildPushObject(userId, title, content, action);
        PushResult pushResult = null;
        try {
            pushResult = jpushClient.sendPush(payload);
            return pushResult;
        } catch (Exception e) {
            log.error("极光推动错误信息", e);
            return null;
        }
    }
}
